package com.gome.ocean.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gome.ocean.common.constants.Constants;


/**
 * Created by liuqingxia on 2016/2/16.
 */
public class DateConverter implements Converter  {
    private final Logger logger = LoggerFactory.getLogger(DateConverter.class);

    @Override
    public <T> T convert(Class<T> type, Object value) {
        if (null == value){
            throw new NullPointerException("The argument value is null");
        }
        if (!(value instanceof String)){
            throw new IllegalArgumentException("The argument value is not instanceof java.lang.String");
        }
        String valueStr = ((String) value).trim();
        if (StringUtils.isBlank(valueStr)){
            return null;
        }
        if (!valueStr.matches(Constants.REG_DATE_FORMAT)){
            throw new IllegalArgumentException("The argument value does not match the format of yyyy-MM-dd HH:mm:ss");
        }
        Date date = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = df.parse(valueStr);
        } catch (ParseException e) {
            logger.error(e.getMessage(),e);
            e.printStackTrace();
        }
        return (T) date;
    }
}
